package com.surfilter.massdata.spark.task.statistics;

import java.sql.Connection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.surfilter.massdata.spark.util.DateUtil;
import com.surfilter.massdata.spark.util.JdbcUtil;

public class StatisticsTask {
	
	private static final Log log = LogFactory.getLog(StatisticsTask.class);
	
	public static void main(String[] args) {
		long start=System.currentTimeMillis();
		long temp=start;
		long temp_end=start;
		double exectime=0.0;
		
		Connection conn = null;
		try{
			String dayStr = ""; 
			if(args.length > 0){
				//传入日期格式：20170703
				dayStr = args[0];
			}
			Date date = getExecDate(DateUtil.getYesterday(),dayStr);
			log.info("统计时间："+DateUtil.getCurrentymd(date));
			
			conn = JdbcUtil.getConnection();
			
			//周表统计
			WeekStatisticsTask.weekStatistics(date, conn);
			
			temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("WeekStatisticsTaskn exectime: "+exectime+" min........................");
			
			//月表统计
			MonthStatisticsTask.monthStatistics(date, conn);
			
			temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("MonthStatisticsTask exectime: "+exectime+" min........................");
			
			//季度表统计
			QuarterStatisticsTask.quarterStatistics(date, conn);
			
			temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("QuarterStatisticsTask exectime: "+exectime+" min........................");
			
			//年表统计
			YearStatisticsTask.yearStatistics(date, conn);
			
			temp_end=System.currentTimeMillis();
            exectime=(temp_end-temp)*1.0/(1000*60);
            temp=temp_end;
			System.out.println("YearStatisticsTask exectime: "+exectime+" min........................");
		}catch(Exception e){
			if(log.isErrorEnabled()){
				log.error(e.getMessage(),e);
			}
		}finally{
			JdbcUtil.close(conn);
		}
		
		long end=System.currentTimeMillis();
		double min=(end-start)*1.0/(1000*60);
		System.out.println("statistics:exectime: "+min+" min............");
	}
	
	public static Date getExecDate(Date date,String dayStr) {
		if (StringUtils.isNotBlank(dayStr)) {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			try {
				date = sdf.parse(dayStr);
			} catch (ParseException e) {
				if(log.isErrorEnabled()){
					log.error(e.getMessage(),e);
				}
			}
		}
		return date;
	}
}
